#!/usr/bin/python
# coding:utf-8

import os
import time
import win32api, win32con, win32gui
from urllib import request
from PIL import Image
from datetime import datetime, timezone, timedelta



class DateTimeUtil(object):

    @staticmethod
    def gmt_str_convert_datetime(gmt_str):
        '''
        将 gmt字符串 转化为 utc时间
        :param gmt_str: gmt字符串 例如 'Wed, 12 Jul 2017 07:37:10 GMT'
        :return: utc时间
        '''
        utc_datetime = datetime.strptime(gmt_str, '%a, %d %b %Y %H:%M:%S GMT')
        return utc_datetime

    @staticmethod
    def local_convert_utc(local_datetime):
        '''
        将 本地时间 转换为 UTC时间
        :param local_time: 本地时间
        :return: UTC时间
        '''
        return local_datetime - __class__._get_local_and_utc_offset()

    @staticmethod
    def utc_convert_local(utc_datetime):
        '''
        将 UTC时间 转换为 本地时间
        :param utc_time: 
        :return: 本地时间
        '''
        return utc_datetime + __class__._get_local_and_utc_offset()

    @staticmethod
    def _get_local_and_utc_offset():
        '''
        获得 本地 与 UTC 时间差
        :return: 
        '''
        timestamp = time.time()
        local = datetime.fromtimestamp(timestamp)
        utc = datetime.utcfromtimestamp(timestamp)
        offset = local - utc
        return offset

    @staticmethod
    def get_network_datetime(url=''):
        '''
        获得网络时间
        :param url: url地址
        :return: 当前时区的时间
        '''
        if url is None or 0 == len(url):
            url = 'https://www.baidu.com/'
        res = request.urlopen(url)
        date_str = res.info().get('date')
        utc_datetime = __class__.gmt_str_convert_datetime(date_str)
        return __class__.utc_convert_local(utc_datetime)


def set_local_datetime(now):
    '''
    设置 当前时间
    :param now: 当前时间
    :return: 
    '''
    utc = DateTimeUtil.local_convert_utc(now)
    set_system_datetime(utc)


def set_system_datetime(now):
    '''
    设置系统时间
    :param now: 系统时间, 应该是 utc时间
    :return: 
    '''
    win32api.SetSystemTime(now.year, now.month, now.isoweekday(), now.day, now.hour, now.minute, now.second, 0)


def get_bing_wallpaper(save_dir=''):
    '''
    获得 bing 的壁纸
    :param save_dir: 保存路径
    :return: 壁纸的完整路径
    '''
    print('get wallpaper info.')
    url = 'http://cn.bing.com'
    res = request.urlopen(url)
    data = res.read()
    res.close()
    data = data.decode('utf-8',errors='ignore')

    # get image url
    url_pre = 'g_img={url: \"'
    url_start = data.find(url_pre) + len(url_pre)
    url_end = data.find('\"', url_start)
    img_url = url + data[url_start:url_end]

    # get image name
    name_pre = '<a id=\"sh_cp\" class=\"sc_light\" title=\"'
    name_start = data.find(name_pre) + len(name_pre)
    name_end = data.find('\"', name_start)
    img_name = data[name_start:name_end] + '.jpg'
    img_name = img_name.replace('<', ' ').replace('>', ' ').replace('|', ' ')\
                .replace(':', ' ').replace('\"', ' ').replace('*', ' ').replace('?', ' ')\
                .replace('/', ' ').replace('\\', ' ')

    if save_dir is None or 0 == len(save_dir):
        save_dir = 'C:/Users/Public/Pictures/wallpaper/'
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    full_path = save_dir + img_name
    if not os.path.exists(full_path):
        print('download wallpaper.')
        request.urlretrieve(img_url, full_path)
    print('download wallpaper complete.')
    return full_path


def set_wallpaper_from_bmp(bmp_path):
    # 打开指定注册表路径
    reg_key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
    # 最后的参数: 2拉伸,0居中,6适应,10填充,0平铺
    win32api.RegSetValueEx(reg_key, "WallpaperStyle", 0, win32con.REG_SZ, "2")
    # 最后的参数: 1表示平铺,拉伸居中等都是0
    win32api.RegSetValueEx(reg_key, "TileWallpaper", 0, win32con.REG_SZ, "0")
    # 刷新桌面
    win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, bmp_path, win32con.SPIF_SENDWININICHANGE)


def set_wallpaper(img_path):
    # 把图片格式统一转换成bmp格式,并放在源图片的同一目录
    img_dir = os.path.dirname(img_path)
    bmpImage = Image.open(img_path)
    new_bmp_path = os.path.join(img_dir, 'wallpaper.bmp')
    bmpImage.save(new_bmp_path, "BMP")
    set_wallpaper_from_bmp(new_bmp_path)


if __name__ == '__main__':
    network_datetime = DateTimeUtil.get_network_datetime('http://cn.bing.com')
    #set_local_datetime(network_datetime)
    wallpaper = get_bing_wallpaper()
    if wallpaper:
        set_wallpaper(wallpaper)